Sys.setenv(JAVA_HOME='/usr/local/software/spack/spack-0.11.2/opt/spack/linux-rhel7-x86_64/gcc-5.4.0/jdk-8u141-b15-p4aaoptkqukgdix6dh5ey236kllhluvr/jre') #Ubuntu cluster
#Sys.setenv(JAVA_HOME= "/usr/lib/jvm/java-11-openjdk-amd64")

.libPaths("/home/hs621/renv/lib/R/library")

## Load packages
library(nlrx)
library(dplyr)
#library(rcartocolor)
#library(ggthemes) 
library(feather)

# Office
netlogopath <- file.path("/usr/local/Cluster-Apps/netlogo/6.0.4")
outpath <- file.path("/home/hs621/github/chapter5")



## Step1: Create a nl obejct:
nl <- nl(nlversion = "6.0.4",
         nlpath = netlogopath,
         modelpath = file.path(outpath, "CBD_Cars_July01.nlogo"),
         jvmmem = 1024)


#chosen_evalticks <- c(28000:29000, 79000:83000, 119000:120000)
chosen_evalticks <- c(28000:29000)

## Step2: Add Experiment
nl@experiment <- experiment(expname = "nlrx_spatial",
                            outpath = outpath,
                            repetition = 1,      
                            tickmetrics = "true",
                            idsetup = "setup",   
                            idgo = "go",
                            runtime = 29000,
                            evalticks= chosen_evalticks,
                            metrics = c("mean-pm10",
                                        "Jongno_p",
                                        "JongnoKerb_p",
                                        "Samil_p",
                                        "Sejong_p",
                                        "Pirum_p",
                                        "Yulgok_p",
                                        "Drivers_p",
                                        "Walkers_p"
                                        ),
                            variables = list('car_ratio' = list(min=.025, max=.075, step=.025, qfun="qunif"),
                                             'health_loss' = list(min=.01, max=.05, step=.02, qfun="qunif")),
                            constants = list('medication' = 1,
                                             "emission-factor" = 5,
                                             'awareness' = "\"no\"")  
)

# Evaluate if variables and constants are valid:
eval_variables_constants(nl)

nl@simdesign <- simdesign_ff(nl = nl, nseeds = 2)
#nl@simdesign <- simdesign_simple(nl = nl, nseeds = 1)
#nl@simdesign <- simdesign_lhs(nl, samples=300, nseeds=1, precision=0)

library(future)
plan(multisession)

# Step4: Run simulations:
init <- Sys.time()
#results <- run_nl_all(nl = nl)
results <- run_nl_all(nl, split=10)
Sys.time() - init

gc()
 
 results$`random-seed`[1]
 
saveRDS(results, file = "FF.rds")
write_feather(results, paste("CBD_FF_", results$`random-seed`[1], ".feather", sep = ""))



